package com.jh.track.admin.api;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jh.track.admin.api.rpc.UserService;
import com.jh.track.admin.pojo.dto.UserDTO;
import com.jh.track.admin.pojo.entity.SysUser;
import com.jh.track.admin.pojo.entity.SysUserRole;
import com.jh.track.admin.service.ISysUserRoleService;
import com.jh.track.admin.service.ISysUserService;

import com.jh.track.common.core.result.Result;
import com.jh.track.common.core.result.ResultCode;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：xy
 * @date ：Created in 2021/4/22 23:36
 * @description：
 * @version: v 1.0.0
 * @email: xy100826@163.com
 */
@DubboService(version = "${service.version}")
public class UserServiceImpl implements UserService {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysUserRoleService iSysUserRoleService;
    @Override
    public Result<UserDTO> getUserByUsername(String username) {
        SysUser user = iSysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));

        // 用户不存在，返回自定义异常，让调用端处理后续逻辑
        if (user == null) {
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }

        // Entity->DTO
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user, userDTO);

        // 获取用户的角色ID集合
        List<Long> roleIds = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, user.getId())
        ).stream().map(item -> item.getRoleId()).collect(Collectors.toList());
        userDTO.setRoleIds(roleIds);

        return Result.success(userDTO);
    }
}
